package com.yanqu.road.server.cmd.union.cross;

import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.entity.enums.eUnionSyncType;
import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.entity.union.cross.CrossUnionInfo;
import com.yanqu.road.entity.union.cross.CrossUnionMember;
import com.yanqu.road.logic.pb.CrossUnionPb;
import com.yanqu.road.pb.union.UnionProto;
import com.yanqu.road.pb.union.cross.CrossUnionProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.command.Command;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.twins.TwinsModule;
import com.yanqu.road.server.gameplayer.module.player.EarnSpeedModule;
import com.yanqu.road.server.manger.palace.PalaceActivity;
import com.yanqu.road.server.manger.palace.PalaceActivityMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.union.CrossUnionMgr;
import com.yanqu.road.server.manger.union.CrossUnionNotifyMgr;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.Protocol;
import io.netty.channel.ChannelHandlerContext;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Cmd(code = Protocol.S_CROSS_UNION_BROADCAST_FROM_CROSS, desc = "商会变化广播")
public class CrossUnionChangeBroadcastCmdFromCross implements Command {

    @Override
    public void execute(ChannelHandlerContext ctx, YanQuMessage packet) throws Exception {

        CrossUnionProto.CrossUnionChangeBroadcastMsg broadcastMsg = CrossUnionProto.CrossUnionChangeBroadcastMsg.parseFrom(packet.getBytes());
        //变化类型
        int syncType = broadcastMsg.getSyncType();
        //商会
        CrossUnionInfo unionInfo = CrossUnionPb.parseCrossUnionInfo(broadcastMsg.getUnion());
        //商会成员
        Map<Long, CrossUnionMember> memberMap = new ConcurrentHashMap<>();
        for (CrossUnionProto.CrossUnionMemberTemp memberTemp : broadcastMsg.getMemberList()) {
            CrossUnionMember member = CrossUnionPb.parseCrossUnionMember(memberTemp);
            memberMap.put(member.getUserId(), member);
        }

        //加入或者退出的玩家
        CrossUnionMember changeMember = null;
        if(broadcastMsg.hasChangeMember()){
            long targetId = broadcastMsg.getChangeMember().getUserId();
            if(memberMap.containsKey(targetId)){
                changeMember = memberMap.get(targetId);
            }else {
                changeMember = CrossUnionPb.parseCrossUnionMember(broadcastMsg.getChangeMember());
            }
        }

        //变更缓存
        CrossUnionMgr.update(syncType, unionInfo, memberMap, changeMember);

        //同步给客户端
        if(syncType == eUnionSyncType.Normal.getValue() || syncType == eUnionSyncType.DeleteUnion.getValue()){
            UnionProto.UnionDetailMsg.Builder detailMsg = broadcastMsg.getMsg().toBuilder();
            for (Map.Entry<Long, CrossUnionMember> entry : memberMap.entrySet()) {
                if(entry.getValue().getServerId() == GameServer.getInstance().getServerId()){
                    GamePlayer player = GamePlayerMgr.getOnlinePlayer(entry.getKey());
                    if(player != null){
                        player.getModule(EarnSpeedModule.class).scheduleAddSilver();
                        player.sendPacket(Protocol.U_UNION_DETAIL, detailMsg);
                        CrossUnionMgr.getLogger().debug("{} U_UNION_DETAIL", player.getUserId());
                    }
                    if(syncType == eUnionSyncType.DeleteUnion.getValue()){
                        if(player != null){
                            player.getUserInfo().setUnionUid("");
                            player.notifyListener(eGamePlayerEventType.JoinUnionActivityCondition.getValue(),player.getUserInfo());
                            UserMgr.addNeedUpdateToCrossMap(player.getUserId(), player.getUserInfo());
                        }else {
                            UserInfo userInfo = UserMgr.getUserInfoInRAM(entry.getKey());
                            if(unionInfo != null){
                                userInfo.setUnionUid("");
                                UserMgr.addNeedUpdateToCrossMap(userInfo.getUserId(), userInfo);
                            }
                        }
                        //皇城处理一下
                        PalaceActivity palaceActivity = PalaceActivityMgr.getInTimePalaceActivity();
                        if(null != palaceActivity){
                            palaceActivity.clearPalaceAideSetting(entry.getKey());
                        }
                    }
                }
            }

        }else if(changeMember != null){

            //影响的玩家
            if(changeMember.getServerId() == GameServer.getInstance().getServerId()){
                UserInfo userInfo = UserMgr.getUserInfoInRAM(changeMember.getUserId());
                if(unionInfo != null) {
                    if (syncType == eUnionSyncType.BeKick.getValue() || syncType == eUnionSyncType.QuitUnion.getValue()) {
                        userInfo.setUnionUid("");
                        //皇城处理一下
                        PalaceActivity palaceActivity = PalaceActivityMgr.getInTimePalaceActivity();
                        if(null != palaceActivity){
                            palaceActivity.clearPalaceAideSetting(userInfo.getUserId());
                        }
                    }
                    if (syncType == eUnionSyncType.JoinUnion.getValue() || syncType == eUnionSyncType.CreateUnion.getValue()) {
                        userInfo.setUnionUid(unionInfo.getUnionUid());
                    }
                    UserMgr.addNeedUpdateToCrossMap(userInfo.getUserId(), userInfo);
                }
                GamePlayer player = GamePlayerMgr.getOnlinePlayer(changeMember.getUserId());
                if(player != null){
                    player.getModule(EarnSpeedModule.class).scheduleAddSilver();
                    UnionProto.UnionDetailMsg.Builder messageBuilder = broadcastMsg.getMsg().toBuilder();
                    if(syncType == eUnionSyncType.SetPosition.getValue()){
                        messageBuilder.setType(eUnionSyncType.Normal.getValue());
                    }
                    player.sendPacket(Protocol.U_UNION_DETAIL, messageBuilder);

                    //6.1 绝代改版商会活动得主动生成下数据 免得进不去
                    player.getModule(TwinsModule.class).initSystem();

                    player.notifyListener(eGamePlayerEventType.JoinUnionActivityCondition.getValue(),player.getUserInfo());  //玩家在线才更新
                }
            }

            //下发详情给其他在线玩家
            UnionProto.UnionDetailMsg.Builder detailMsg = broadcastMsg.getMsg().toBuilder();
            detailMsg.setType(eUnionSyncType.Normal.getValue());
            for (Map.Entry<Long, CrossUnionMember> entry : memberMap.entrySet()) {
                if(changeMember.getUserId() == entry.getKey()){
                    continue;
                }
                if(entry.getValue().getServerId() != GameServer.getInstance().getServerId()){
                    continue;
                }
                GamePlayer player = GamePlayerMgr.getOnlinePlayer(entry.getKey());
                if(player != null){
                    player.getModule(EarnSpeedModule.class).scheduleAddSilver();
                    player.sendPacket(Protocol.U_UNION_DETAIL, detailMsg);
                }
            }
        }

        List<CrossUnionMember> list = new ArrayList<>();
        if(syncType == eUnionSyncType.Normal.getValue() || syncType == eUnionSyncType.DeleteUnion.getValue() || syncType == eUnionSyncType.UpGrade.getValue()
            || syncType == eUnionSyncType.ChamberPatrons.getValue()){
            list.addAll(memberMap.values());
        }else {
            list.add(changeMember);
        }

        //通知其他业务
        CrossUnionNotifyMgr.notifyListener(syncType, broadcastMsg.getPlayerId(), unionInfo, list);
    }
}
